package org.wenbo.override.core;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class App extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public App() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		response.setCharacterEncoding("utf-8");
		String dir = request.getRequestURI().substring(
				request.getRequestURI().lastIndexOf("/"));
		String act = dir.replace("/", "");

		if (act.length() < 1) {
			request.getRequestDispatcher("index.shtml").forward(request, response);
			return;
		}

		act = act.replace(".html", "");
		act = act.replace(".htm", "");
		act = act.replace(".aspx", "");
		act = act.replace(".php", "");
		act = act.replace(".cgi", "");
		act = act.replace(".shtml", "");
		act = act.replace(".xhtml", "");
		act = act.replace(".asp", "");
		act = act.replace(".wenbo", "");
		act = act.replace(".amaya", "");
		act = act.replace(".py", "");
		act = act.replace(".c", "");
		act = act.replace(".zip", "");
		act = act.replace(".rar", "");

		act = act.substring(0, 1).toUpperCase()
				+ act.substring(1, act.length());

		String fn = request.getParameter("fn");
		if (fn == null) {
			fn = "index";
		}

		try {
			Class<?> c = Class.forName("app.page." + act);
			try {
				Object o = c.newInstance();
				try {
					Method doFn = c.getMethod(fn, null);
					Method set = c.getMethod("set",
							new Class[] { HttpServletRequest.class,
									HttpServletResponse.class });
					try {
						set.invoke(o, request, response);
						doFn.invoke(o, null);
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
